package com.ruoyi.web.controller.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class AESUtil {
    /**算法名称**/
    public static final String KEY_ALGORITHM = "AES";
    /**算法名称/加密模式/填充方式**/
    public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    /** 编码 **/
    public static final String CHARSET_NAME = "UTF-8";

    public static final String APP_SECRET= "PSzpJIjwrSeESixIgpytugXd3ZwHwHusQ6WZ9bwRzPU";

    public static void main(String[] args) throws Exception {
        String source = "Store004";
        System.out.println("原文: " + source);
        String key = APP_SECRET.substring(0,16);
        String encryptData = encrypt(source, key);
        System.out.println("加密后: " + encryptData);
        String decryptData = decrypt(encryptData, key);
        System.out.println("解密后: " + decryptData);
//

//        String body = "{\"encryptPhone\": \"twzjBHOHRWShqQ1H5sXyHg==\",\"deliveryMethod\": \"REDIRECT\",\"openChannel\": 1,\"bizLine\": \"ENERGY\"}";
//
//        String res = DigestUtils.md5Hex(body);
//        System.out.println(res);
    }

    /**
     *
     * 生成密钥key对象
     * @param keyStr 密钥字符串
     * @return 密钥对象
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws Exception
     */
    private static SecretKey keyGenerator(String keyStr) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(keyStr.getBytes(CHARSET_NAME), KEY_ALGORITHM);
        return secretKey;
    }

    /**
     * 加密数据
     * @param data 待加密数据
     * @param key 密钥
     * @return 加密后的数据
     */
    public static String encrypt(String data, String key) throws Exception {
        Key secretKey = keyGenerator(key);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes(CHARSET_NAME));
        // 实例化Cipher对象，它用于完成实际的加密操作
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 初始化Cipher对象，设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] results = cipher.doFinal(data.getBytes(CHARSET_NAME));
        // 执行加密操作。加密后的结果通常都会用Base64编码进行传输
        return Base64.getEncoder().encodeToString(results);
    }

    /**
     * 解密数据
     * @param data 待解密数据
     * @param key 密钥
     * @return 解密后的数据
     */
    public static String decrypt(String data, String key) throws Exception {
        Key secretKey = keyGenerator(key);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes(CHARSET_NAME));
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
    }

}
